package nancal.mp.mvc.dev

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import nancal.mp.client.integration.SysCacheClient
import nancal.mp.db.mongo.entity.dev.*
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.*
import nbcp.base.db.CodeName
import nbcp.base.db.IdNameUrl
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.CodeUtil
import nbcp.mvc.sys.*
import nbcp.myoql.db.mongo.*

import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * Created by CodeGenerator at 2022-04-29 15:19:26
 */
@Api(description = "应用部署设置服务器", tags = arrayOf("AppDeploySetting"))
@RestController
@RequestMapping("/dev/app-deploy-setting")
class AppDeploySettingAutoController {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    @PostMapping("/clear-nexus")
    fun clearNexus(@Require id: String, @Require number: Int): JsonResult {
        var setting =  mor.dev.appDeploySetting.queryById(id).toEntity()
            .throwIfNull { "找不到数据" }

        setting.nexusServer.nexusHttpUrl.throwIfNull { "nexusHttpUrl不能为空" }

        return JsonResult()
    }

    @PostMapping("/set-active")
    fun setActive(@Require id: String): JsonResult {
        mor.dev.appDeploySetting.updateById(id)
            .set { it.isActive to true }
            .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult.error("更新失败")
        }

        mor.dev.appDeploySetting.update()
            .where { it.isActive mongoEquals true }
            .where { it.id mongoNotEquals id }
            .set { it.isActive to false }
            .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult.error("更新失败")
        }

        myMemoryCaches.brokeWithMatch(mor.dev.appDeploySetting.userDefineTableName)

        return JsonResult()
    }

    @ApiOperation("列表")
    @PostMapping("/list")
    fun list(
        id: String, //当列表列新一条后，刷新时使用
        name: String,
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>,
        request: HttpServletRequest
    ): ListResult<AppDeploySetting> {

        mor.dev.appDeploySetting.query()
            .apply {
                if (id.HasValue) {
                    this.where { it.id mongoEquals id }
                }
                if (name.HasValue) {
                    this.where { it.name mongoLike name }
                }
            }
            .withPager(query)
            .toListResult()
            .apply {
//                if (this.data.any()) {
//                    var userSetting = appDeploySettingClient.getConfig("app.deploy-setting-code")
//                    if (userSetting.HasValue) {
//                        this.value = userSetting
//                    }
//                }

                return this;
            }
    }

    class ApiModel : IdNameUrl() {
        var code = "";
        var isActive = false;
    }

    @ApiOperation("列表")
    @PostMapping("/apis")
    fun items(): ListResult<ApiModel> {
        mor.dev.appDeploySetting.query()
            .toList()
            .map {
                ApiModel().apply {
                    this.id = it.id;
                    this.name = it.name
                    this.url = it.mpIntegrationApiUrl
                    this.code = it.code
                    this.isActive = it.isActive
                }
            }
            .apply {
                return ListResult.of(this)
            }
    }

    @GetMapping("/detail")
    fun currentSetting(code: String): ApiResult<AppDeploySetting> {
        return ApiResult.of(
            mor.dev.appDeploySetting.getAppDeploySetting(code)
        )
    }


    @ApiOperation("详情")
    @PostMapping("/copy-from/{id}")
    fun copyFrom(
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<String> {
        mor.dev.appDeploySetting.queryById(id)
            .toEntity()
            .apply {
                if (this == null) {
                    return ApiResult.error("找不到数据")
                }

                this.id = "";
                this.code = this.code + "-" + CodeUtil.getCode()

                this.isActive = false

                mor.dev.appDeploySetting.doInsert(this);

                return ApiResult.of(this.id)
            }
    }


    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<AppDeploySetting> {
        mor.dev.appDeploySetting.queryById(id)
            .toEntity()
            .apply {
                if (this == null) {
                    return ApiResult.error("找不到数据")
                }

                return ApiResult.of(this)
            }
    }

    @PostMapping("/integration-apis")
    fun getIntegrations(): ApiResult<Array<CodeName>> {
        var list = mor.dev.appDeploySetting.aggregate()
            .rawGroup {
                JsonMap(
                    "_id" to "$" + it.mpIntegrationApiHost.toString(),
                    it.code.toString() to JsonMap("${'$'}max" to it.code.toString())
                )
            }
            .limit(0, 99)
            .toMapList()
            .map {
                return@map CodeName(it.get("code").AsString(), it.get("_id").AsString())
            }
            .toTypedArray();

        return ApiResult.of(list)
    }

    @Autowired
    lateinit var sysCacheClient: SysCacheClient

    @ApiOperation("更新")
    @PostMapping("/save")
    fun save(
        @org.springframework.web.bind.annotation.RequestBody entity: AppDeploySetting,
        request: HttpServletRequest
    ): ApiResult<String> {
        //鉴权
        var userId = request.UserId;

        var ret = mor.dev.appDeploySetting.updateWithEntity(entity)
            .withColumns(request.requestParameterKeys)
            .run {
                if (entity.id.HasValue) {
                    return@run this.execUpdate()
                } else {
                    return@run this.execInsert()
                }
            }

        if (ret == 0) {
            return ApiResult.error("更新失败")
        }



        try {
            sysCacheClient.broke(mor.dev.appDeploySetting.userDefineTableName + ".**")
        } catch (e: Exception) {
            logger.info(e.message);
        }

        return ApiResult.of(entity.id)
    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    fun delete(
        @Require id: String,
        request: HttpServletRequest
    ): JsonResult {
        //鉴权
        var userId = request.UserId

        var entity = mor.dev.appDeploySetting.queryById(id).toEntity()
        if (entity == null) {
            return JsonResult.error("找不到数据")
        }

        mor.dev.appDeploySetting.deleteById(id)
            .exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
                //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                return JsonResult()
            }
    }

    @ApiOperation("当前")
    @PostMapping("/current")
    fun current(): ApiResult<AppDeploySetting> {
        return ApiResult.of(mor.dev.appDeploySetting.getAppDeploySetting())
    }

}